
<template>
    <div class="app-container">
      <search-header
        v-show="boo.showSearch"
        :select-prop="selectProp"
        @search-action="searchAction"
      ></search-header>

      <div class="app-permission-container flex-between mb8">
        <span class="page-list-title">商家列表</span>
        <div class="action-content">
          <el-button type="primary" size="mini" @click="exportData" v-hasPermi="['admin:acddShop:export']"
          >导出</el-button>
          <el-button type="primary" size="mini" @click="showDialog('store', 'add')"
          v-hasPermi="['admin:acddShop:add']">新增</el-button>
        </div>
      </div>
      <div class="app-table-container">
        <el-table v-loading="boo.loading" :data="list" border>
          <el-table-column
            label="商户类型"
            align="center"
            key="shopType"
            prop="shopType"
            :show-overflow-tooltip="true" >
            <template slot-scope="{row}">
              {{ row['shopType'] | numToStr(dictsList, 'shopType') }}
            </template>
          </el-table-column>
          <el-table-column
            label="版本类型"
            align="center"
            key="versionType"
            prop="versionType"
            :show-overflow-tooltip="true" >
            <template slot-scope="{row}">
              {{ row['versionType'] | numToStr(dictsList, 'versionType') }}
            </template>
          </el-table-column>
          <el-table-column
            label="版本名称"
            align="center"
            key="shopTypeName"
            prop="shopTypeName"
            :show-overflow-tooltip="true" >
            <template slot-scope="{row}">
              {{ row.shopTypeName || '---' }}
            </template>
          </el-table-column>
          <el-table-column
            label="门店图片"
            align="center"
            key="imgUrlVos"
            prop="imgUrlVos">
            <template slot-scope="{row}">
              <rh-preview :list="row.imgUrlVos"></rh-preview>
            </template>
          </el-table-column>
          <el-table-column
            label="商家名称"
            align="center"
            key="shopName"
            prop="shopName"
            :show-overflow-tooltip="true" /> 
          <el-table-column
            label="渠道"
            align="center"
            key="channel"
            prop="channel"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="经营地址"
            align="center"
            key="shopAddress"
            prop="shopAddress"/>
          <el-table-column
            label="负责人"
            align="center"
            key="head"
            prop="head"
            :show-overflow-tooltip="true"/>
          <el-table-column
            label="负责人电话"
            align="center"
            key="headPhone"
            prop="headPhone" />
          <el-table-column
            label="入驻时间"
            align="center"
            key="startTime"
            prop="startTime"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="核销总计"
            align="center"
            key="writeOffNum"
            prop="writeOffNum"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="状态"
            align="center"
            key="cooperateState"
            prop="cooperateState"
            :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <el-tag :type="row['cooperateState'] == 1 ? 'danger' : 'success'">
                {{ row['cooperateState'] | numToStr(dictsList, 'cooperateState') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="120"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="{row}">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit" v-hasPermi="['admin:acddShop:edit']"
                @click="showDialog('store', 'edit', row)" 
                :loading="row.isEdit"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="text" v-hasPermi="['admin:acddShop:pause']"
                icon="el-icon-video-pause"
                :loading="row.isControl"
                @click="controlTypeRow(row)"
                >
                {{ row.cooperateState ? '启用' : '停用' }}
                </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="other.total > 0"
          :total="other.total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      
      <dialog-normal
        ref="dialog-store"
        :dialog-prop="{
          title: dialogStore.title,
          height: '55vh',
          width: '60%',
          submit: '确定',
          close: '取消'
        }"
        @normal-submit="submitDialog('store', dialogStore.currentItem)"
        >
        <template #dialog-content v-if="$refs[`dialog-store`] && $refs[`dialog-store`].showDialog">
          <el-form
            class="form-content"
            ref="store-form" label-position="left"
            :model="dialogStore.currentItem"
            label-width="120px">
            <div class="form-title">门店照片</div>
            <el-form-item class="form-content-item"
              label="" prop="imgUrlVos"
              :rules="{ required: true, message: `请上传门店图片`, trigger: 'change'}">
              <div class="form-val no-border" style="width: 100%">
                <imageUpload
                  v-model="dialogStore.currentItem['imgUrlVos']"
                  :limit="3" :isShowTip="false" />
              </div>
            </el-form-item>
            <div class="form-title">商家信息</div>
            <el-form-item class="form-content-item"
                label="商户类型：" prop="shopType"
                :rules="{ required: true, message: `此项不能为空`, trigger: 'change'}">
              <el-col :span="12">
                <div class="form-val flex-normal" style="width: 80%;">
                <el-select v-model="dialogStore.currentItem['shopType']" placeholder="请选择商户类型"
                @change="otherTypeChange">
                  <el-option
                    v-for="item in getDictItem('shopType')"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue">
                  </el-option>
                </el-select>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="form-val flex-normal" style="width: 80%;">
                <el-select v-model="dialogStore.currentItem['versionType']" placeholder="请选择版本类型"
                @change="otherTypeChange">
                  <el-option
                    v-for="item in getDictItem('versionType')"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue">
                  </el-option>
                </el-select>
                </div>
              </el-col>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="版本名称：" prop="shopTypeId">
              <div class="form-val flex-normal" style="width: 90%;">
                <el-select v-model="dialogStore.currentItem['shopTypeId']" placeholder="请选择版本名称"
                @change="shopTypeChange($event)">
                  <el-option
                    v-for="item in shopTypeList"
                    :key="item.val"
                    :label="item.versionName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="商户年费：" prop="yearFee"
                :rules="[
                  { required: true, message: `商户年费不能为空`, trigger: 'input',},
                  { validator: validateMoney, trigger: 'blur'}
                ]">
                <div class="form-val flex-normal">
                  <el-input v-model="dialogStore.currentItem['yearFee']" placeholder="请输入商户年费"></el-input>
                </div>
                <span class="code-desc-unit">A类商户标准年费：{{dialogStore.shopType['yearFee'] || '0.00'}}元/年</span>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="商家名称：" prop="shopName"
                :rules="{ required: true, message: `商家名称不能为空`, trigger: 'blur'}">
                <div class="form-val flex-normal">
                  <el-input v-model="dialogStore.currentItem['shopName']" placeholder="请输入店铺名称"></el-input>
                </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="商家地址：" prop="shopAddress"
                :rules="{ required: true, message: `商家地址不能为空`, trigger: ['blur', 'change']}">
              <div class="form-val flex-normal">
                <el-input readonly v-model="dialogStore.currentItem['shopAddress']" placeholder="请选择店铺地址" @click.native="showDialog('map', 'view')">
                  <el-button slot="suffix" type="text" size="medium" icon="el-icon-search" @click="showDialog('map', 'view')"></el-button>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="负责人：" prop="head"
                :rules="{ required: true, message: `负责人不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-input v-model="dialogStore.currentItem['head']"></el-input>
              </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="负责电话：" prop="headPhone"
                :rules="{ required: true, message: `负责电话不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-input v-model="dialogStore.currentItem['headPhone']"></el-input>
              </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="客服电话：" prop="account"
                :rules="[
                  { required: true, message: `客服电话不能为空`, trigger: 'blur'}
                ]">
              <div class="form-val flex-normal">
                <el-input v-model="dialogStore.currentItem['csTel']"></el-input>
              </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="登录账号：" prop="account"
                :rules="[
                { required: true, message: `登录账号不能为空`, trigger: 'blur'},
                { validator: validatePhoneNum, trigger: 'blur'}
              ]">
              <div class="form-val flex-normal">
                <el-input v-model="dialogStore.currentItem['account']"></el-input>
              </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="密码：" prop="password"
                :rules="{ required: true, message: `密码不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-input v-model="dialogStore.currentItem['password']" type="password"></el-input>
              </div>
              <el-button :loading="boo.randomPassword" @click="randomPassword" class="code-btn-unit" type="text">生成随机密码</el-button>
            </el-form-item>
            
            <el-form-item class="form-content-item"
                label="合作状态：" prop="cooperateState"
                :rules="{ required: true, message: `合作状态不能为空`, trigger: 'change'}">
              <div class="form-val no-border flex-normal">
                <el-radio-group v-model="dialogStore.currentItem.cooperateState">
                  <el-radio v-for="radio in getDictItem('status')" :key="radio.dictValue" :label="radio.dictValue">{{radio.dictLabel}}</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="入驻时间：" prop="startTime"
                :rules="{ required: true, message: `入驻时间不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-date-picker clearable size="small" 
                  v-model="dialogStore.currentItem['startTime']" type="date" 
                  value-format="yyyy-MM-dd"
                  placeholder="请选择入驻时间">
                </el-date-picker>
              </div>
            </el-form-item>
            <el-form-item class="form-content-item"
                label="到期时间" prop="endTime"
                :rules="{ required: true, message: `到期时间不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-date-picker clearable size="small"
                  v-model="dialogStore.currentItem['endTime']" type="date" 
                  value-format="yyyy-MM-dd"
                  placeholder="请选择到期时间">
                </el-date-picker>
              </div>
            </el-form-item>
          </el-form>
        </template>
      </dialog-normal>
      <dialog-normal
        ref="dialog-map"
        :dialog-prop="{
          title: '选择位置',
          width: '60%',
          submit: '确定',
          close: '取消'
        }"
        @normal-submit="submitDialog('map', dialogStore.shopInfo)">
        <template #dialog-content v-if="$refs[`dialog-map`] && $refs[`dialog-map`].showDialog">
          <draw-map v-model="dialogStore.shopInfo"/>
        </template>
      </dialog-normal>
    </div>
  </template>
  
  <script>
  import {
    getShopList, addShop, editShop, getShopDetail, controlShop, randomPassword, getShopCooperatelist, exportData
  } from "@/api/userManage/admin-shop.js";
  import {getVersonList} from '@/api/register'
  import {isDecimal, isPhoneNum} from '@/utils/tools.js'
  export default {
    name: "List",
    components: {
      "search-header": () => import("@/rhComponents/searchHeader/index"),
      "dialog-normal": () => import("@/rhComponents/dialog/normal-dialog"),
      'draw-map': () => import('@/rhComponents/map/draw-map.vue'),
      'rh-preview': () => import('@/rhComponents/image-preview/index.vue')
    },
    filters: {
      numToStr(num, list, type){
        let index = list.findIndex(item => item.name == type)
        if(index == -1) return '未定义参数'
        let idx = list[index].child.findIndex(i => i.dictValue == num)
        if(idx == -1) return '---'
        return list[index].child[idx].dictLabel
      }
    },
    data() {
      return {
        selectProp: JSON.parse(JSON.stringify(this.$getSearchHeader(this))),
        boo: {
          loading: false, // 遮罩层
          multiple: true, // 非多个禁用
          showSearch: true, // 显示搜索条件
          randomPassword: false,
        },
        other: {
          ids: [], // 选中数组
          total: 0, //总条数
        },
        shopTypeList: [],
        dictsList: [
          { label: "合同状态", name: "cooperateState", deptType: "status", child: [] },
          { label: "版本类型", name: "versionType", deptType: "versionType", child: [] },
          { label: "商户类型", name: "shopType", deptType: "shopType", child: [] }
        ],
        // 地块列表
        list: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        dialogStore: {
          title: '新建商家',
          currentItem: {},
          showInfo: {
            name: 'XXX店',
            desc: 'XXX街',
            latlng: '22.0,336.0'
          },
          shopType: {}, //选中的商户类型
        },
      };
    },
    mounted(){
      let _self = this
      _self.initGetDicts().then(res => {
        _self.getList()
      })
    },
    methods: {
      exportData(){
        let _self = this
        exportData(`商户列表`).then(res => {
          console.log(res)
        })
      },
      async otherTypeChange(){
        let _self = this
        await _self.queryShopTypeDict()
        _self.$set(_self.dialogStore['currentItem'], 'shopTypeId', '')
        _self.$set(_self.dialogStore['currentItem'], 'yearFee', '')
      },
      getDictItem(name){
        let item = this.dictsList.find(i => i.deptType == name)
        return item.child
      },
      validateMoney: (rule, value, callback) => {
        if (!isDecimal(`${value}`)) {
          callback(new Error('请输入正确的金额'));
        } else {
          callback();
        }
      },
      validatePhoneNum: (rule, value, callback) => {
        if (!isPhoneNum(`${value}`)) {
          callback(new Error('请输入正确手机号'));
        } else {
          callback();
        }
      },
      async queryShopTypeDict(){
        let {shopType, versionType} = this.dialogStore.currentItem
        let params = {
          shopType, versionType
        }
        await getVersonList(params).then(res => {
          this.shopTypeList = res.data
        })
      },
      // 搜索条件查询
      searchAction(prop) {
        this.queryParams = Object.assign(this.queryParams, prop["params"]);
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 查询用户列表 */
      getList() {
        this.boo.loading = true;
        getShopList(this.queryParams)
          .then((response) => {
            this.list = response.rows;
            this.other.total = response.total;
            this.boo.loading = false;
          })
          .catch(() => {});
      },
      async randomPassword(){
        let _self = this
        _self.boo.randomPassword = true
        await randomPassword().then(res => {
          _self.$set(_self.dialogStore.currentItem, 'password', res.msg)
        })
        _self.boo.randomPassword = false
      },
      controlTypeRow(row){
        let _self = this
        row.isControl = true
        _self.$set(row, 'isControl', true)
        controlShop({id: row.id}).then(res => {
          _self.getList()
          _self.$message.success('操作成功')
        }).catch(() => {
          _self.$set(row, 'isControl', false)
        })
      },
      shopTypeChange(val){
        let _self = this
        let {shopTypeId} = _self.dialogStore.currentItem
        let item = _self.shopTypeList.find(i => i.id == shopTypeId)
        if(!item) return
        _self.dialogStore.shopType = item
        if(!val) return
        _self.$set(_self.dialogStore['currentItem'], 'yearFee', item.yearFee)
      },
      // 事件集合 -- 转发
      actionsMaps(ref, acion, row){
        let _self = this
        let actionsMap = () => {
          return new Map([
            [{ref: 'map', acion: 'view:show'}, async ()=>{  
              await _self.queryShopTypeDict()
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].showDialog = true
              })
            }],
            [{ref: 'map', acion: 'submit'}, ()=>{
              if(!row || !row.desc || !row.latlng){
                _self.$refs[`dialog-${ref}`].loading = false;
                return _self.$message.error('请选择店铺地址')
              }
              _self.$set(_self.dialogStore.currentItem, 'shopAddress', row.desc)
              _self.$set(_self.dialogStore.currentItem, 'latitudeAndLongitude', row.latlng)           
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].loading = false;
                _self.$refs[`dialog-${ref}`].showDialog = false
              })
            }],
            [{ref: 'store', acion: 'add:show'}, ()=>{
              _self.dialogStore.title = '添加商户'
              _self.dialogStore.currentItem = {}
              _self.shopTypeList = []
              _self.dialogStore.shopType = _self.shopTypeList[0] || {}
              _self.$nextTick(() => {
                _self.$refs[`dialog-${ref}`].showDialog = true
              })
            }],
            [{ref: 'store', acion: 'edit:show'}, async ()=>{
              _self.dialogStore.title = '编辑商户'
              _self.$set(row, 'isEdit', true)
              await _self.queryShopTypeDict()
              getShopDetail(row.id).then(res => {
                let {imgUrlVos = [], shopAddress, latitudeAndLongitude} = res.data
                console.log(res.data)
                res.data['imgUrlVos'] = (imgUrlVos || []).map(i => i.url).join(',')
                _self.dialogStore.currentItem = res.data
                _self.dialogStore.shopInfo = {
                  desc: shopAddress,
                  latlng: latitudeAndLongitude
                }
                _self.shopTypeChange()
                _self.$nextTick(() => {
                  _self.$refs[`dialog-${ref}`].showDialog = true
                })
              }).finally(() => _self.$set(row, 'isEdit', false))
            }],
            [{ref: 'store', acion: 'submit'}, ()=>{
              let params = JSON.parse(JSON.stringify(row)), imgArr = []
              if(params.imgUrlVos){
                let arr = params.imgUrlVos.split(',')
                imgArr = arr.map(i => {
                  return {
                    url: i
                  }
                }) 
                params.imgUrlVos = imgArr
              }
              let success = (res, msg) => {
                _self.$message.success(msg)
                _self.getList()
                _self.$nextTick(() => {
                  _self.$refs[`dialog-${ref}`].showDialog = false
                })
              }
              if(params.id){
                editShop(params).then(res => {
                  success(res, '修改成功')
                }).finally(() => {
                  _self.$refs[`dialog-${ref}`].loading = false;
                })
              }else {
                addShop(params).then(res => {
                  _self.queryParams.pageNum = 1
                  success(res, '添加成功')
                }).finally(() => {
                  _self.$refs[`dialog-${ref}`].loading = false;
                })
              } 
            }]
          ])
        }
        let actions = [...actionsMap()].filter(([key,value])=>(key.ref == ref && key.acion == acion))
        actions.forEach(([key,value])=>value.call(this))
      },
      showDialog(ref, type, row) {
        let _self = this;
        if (_self.$refs[`${ref}-form`]) {
          this.resetForm(`${ref}-form`);
        }
        _self.$nextTick(() => {
          _self.actionsMaps(ref, `${type}:show`, row)
        })
      },
      submitDialog(ref, row) {
        let _self = this;
        if(this.$refs[`${ref}-form`]){
          this.$refs[`${ref}-form`].validate((valid) => {
            if (valid) {
              _self.$refs[`dialog-${ref}`].loading = true
              _self.actionsMaps(ref, `submit`, row)
            } else {
              _self.$refs[`dialog-${ref}`].loading = false;
              return false;
            }
          });
        }else{
          _self.$refs[`dialog-${ref}`].loading = true
          _self.actionsMaps(ref, `submit`, row)
        }
      },
    }
  };
  </script>
  <style scoped lang="scss">
  .form-content{
    .form-row{
      display: grid;
      grid-template-rows: repeat(2, 1fr);
      gap: 20px;
    }
    .form-content-item{
      position: relative;
      .code-btn-unit, .code-desc-unit, .code-success-unit{
        position: absolute;
        left: vw(400);
        top: 50%;
        transform: translateY(-50%);
        font-size: vh(13);
      }
      .code-btn-unit{
        color: #0003AA;
        cursor: pointer;
      }
      .code-success-unit{
        color: #0003AA;
      }
    }
    .form-title{
      margin-bottom: vh(20);
      line-height: vh(34);
      font-size: vh(13);
      color: #0003AA;
    }
    .form-val {
      width: vw(360);
      flex-wrap: nowrap;
      &.no-border{
        border: none;
      }
    }
  }
  </style>